import cv2
import numpy as np

img1=cv2.imread('test3.jpg')

img2=cv2.imread('test3.jpg')

img1=cv2.cvtColor(img1,cv2.COLOR_BGR2HSV)
low=(156,43,46)
high=(180,255,255)
img1=cv2.inRange(img1,low,high)
img1=cv2.blur(img1,(3,3))
# kernel = np.ones((1,1),np.uint8)
kernel1=np.ones((7,7),np.uint8)
# img1=cv2.erode(img1,kernel=kernel)
img1=cv2.dilate(img1,kernel=kernel1)

contours,hierarchy=cv2.findContours(img1,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
# print(contours)
width,height=img1.shape
n=input('请输入限制大小：比如印章大概有图片一半大那么请输入3表示宽度或者高度小于图片三分之一的物体不予框选,回车则为默认值')
if n == '':
    n=10
else:
    n=int(n)
temp = np.ones(img2.shape,np.uint8)*255#白色画布
for i in contours:
    x, y, w, h = cv2.boundingRect(i)
    if (w< width/n) or (h < height/n):#面积过小的不框选
        pass
    else:
        cv2.rectangle(temp, (x, y), (x + w, y + h), (0, 255, 0), 2)
        widthRGB,heightRGB,channel=img2.shape
        b,g,r=cv2.split(img2)
        for I in range(x,x+w+1):
            for u in range(y,y+h+1):
                if img2[u,I,2]>100:
                    temp[u,I]=img2[u,I]
                else:
                    temp[u,I]=255



num=7
area=[]
# for c in range(len(contours)):
#     # 面积
#     area.append(cv2.arcLength(contours[c], True))
# for i in range(num):
#     area_id=area.index(max(area))
#     x, y, w, h = cv2.boundingRect(contours[area_id])
#     cv2.rectangle(img2, (x, y), (x + w, y + h), (0, 255, 0), 2)
#     area.remove(max(area))

'''
# (x,y),radius=cv2.minEnclosingCircle(contour)
# cv2.circle(img2,(int(x),int(y)),int(radius),(255,0,255),2)
'''



cv2.imshow('img1',img1)#处理图
cv2.imshow('img2',img2)#原图
cv2.imshow('temp',temp)#结果图
# cv2.imshow('r',r)

cv2.waitKey(0)
cv2.destroyAllWindows()

# gary=cv2.cvtColor(img1,cv2.COLOR_BGR2GRAY)
# b,g,r=cv2.split(img1)
# print(img1.shape)
# ret,thresh=cv2.threshold(r,200,200,cv2.THRESH_BINARY|cv2.THRESH_OTSU)
# cv2.imshow('r',r)
# cv2.imshow('mask',thresh)